package com.irdstudio.rsp.rule.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.rsp.drools.beans.RuleBean;
import com.irdstudio.rsp.drools.beans.RuleResultBean;
import com.irdstudio.rsp.rule.common.BizUtil;
import com.irdstudio.rsp.rule.dao.SRuleCollInfoDao;
import com.irdstudio.rsp.rule.dao.domain.SRuleCollInfo;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.irdstudio.rsp.rule.service.facade.BizRuleLogDetailService;
import com.irdstudio.rsp.rule.dao.BizRuleLogDetailDao;
import com.irdstudio.rsp.rule.dao.domain.BizRuleLogDetail;
import com.irdstudio.rsp.rule.service.vo.BizRuleLogDetailVO;
import com.irdstudio.sdk.beans.core.base.FrameworkService;
/**
 * <p>ServiceImpl: 业务规则日志明细				<p>
 * @author AutoCoder
 * @date 2019-10-30
 */
@Service("bizRuleLogDetailServiceImpl")
public class BizRuleLogDetailServiceImpl implements BizRuleLogDetailService, FrameworkService {
	
	private static Logger logger = LoggerFactory.getLogger(BizRuleLogDetailServiceImpl.class);

	@Autowired
	private BizRuleLogDetailDao bizRuleLogDetailDao;

	@Autowired
	private SRuleCollInfoDao sRuleCollInfoDao;
	
	/**
	 * 新增操作
	 */
	public int insertBizRuleLogDetail(BizRuleLogDetailVO inBizRuleLogDetailVo) {
		logger.debug("当前新增数据为:"+ inBizRuleLogDetailVo.toString());
		int num = 0;
		try {
			BizRuleLogDetail bizRuleLogDetail = new BizRuleLogDetail();
			beanCopy(inBizRuleLogDetailVo, bizRuleLogDetail);
			num = bizRuleLogDetailDao.insertBizRuleLogDetail(bizRuleLogDetail);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:"+ num);
		return num;
	}

	/**
	 * 删除操作
	 */
	public int deleteByPk(BizRuleLogDetailVO inBizRuleLogDetailVo) {
		logger.debug("当前删除数据条件为:"+ inBizRuleLogDetailVo);
		int num = 0;
		try {
			BizRuleLogDetail bizRuleLogDetail = new BizRuleLogDetail();
			beanCopy(inBizRuleLogDetailVo, bizRuleLogDetail);
			num = bizRuleLogDetailDao.deleteByPk(bizRuleLogDetail);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inBizRuleLogDetailVo +"删除的数据条数为"+ num);
		return num;
	}


	/**
	 * 更新操作
	 */
	public int updateByPk(BizRuleLogDetailVO inBizRuleLogDetailVo) {
		logger.debug("当前修改数据为:"+ inBizRuleLogDetailVo.toString());
		int num = 0;
		try {
			BizRuleLogDetail bizRuleLogDetail = new BizRuleLogDetail();
			beanCopy(inBizRuleLogDetailVo, bizRuleLogDetail);
			num = bizRuleLogDetailDao.updateByPk(bizRuleLogDetail);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inBizRuleLogDetailVo +"修改的数据条数为"+ num);
		return num;
	}
	
	/**
	 * 查询操作
	 */
	public BizRuleLogDetailVO queryByPk(BizRuleLogDetailVO inBizRuleLogDetailVo) {
		
		logger.debug("当前查询参数信息为:"+ inBizRuleLogDetailVo);
		try {
			BizRuleLogDetail queryBizRuleLogDetail = new BizRuleLogDetail();
			beanCopy(inBizRuleLogDetailVo, queryBizRuleLogDetail);
			BizRuleLogDetail queryRslBizRuleLogDetail = bizRuleLogDetailDao.queryByPk(queryBizRuleLogDetail);
			if (Objects.nonNull(queryRslBizRuleLogDetail)) {
				BizRuleLogDetailVO outBizRuleLogDetailVo = beanCopy(queryRslBizRuleLogDetail, new BizRuleLogDetailVO());
				logger.debug("当前查询结果为:"+ outBizRuleLogDetailVo.toString());
				return outBizRuleLogDetailVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}


	/**
	 * 查询用户权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<BizRuleLogDetailVO> queryAllOwner(BizRuleLogDetailVO bizRuleLogDetailVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<BizRuleLogDetailVO> list = null;
		try {
			if (StringUtils.isNotBlank(bizRuleLogDetailVo.getSort())) {
				String sort = BizUtil.transferCamelCaseToHyphen(bizRuleLogDetailVo.getSort());
				bizRuleLogDetailVo.setSort(sort);
			}
			if (StringUtils.isBlank(bizRuleLogDetailVo.getOrder())) {
				bizRuleLogDetailVo.setOrder("asc");
			}
			List<BizRuleLogDetail> bizRuleLogDetails = bizRuleLogDetailDao.queryAllOwnerByPage(bizRuleLogDetailVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:"+ bizRuleLogDetails.size());
			pageSet(bizRuleLogDetails, bizRuleLogDetailVo);
			list = (List<BizRuleLogDetailVO>) beansCopy(bizRuleLogDetails, BizRuleLogDetailVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<BizRuleLogDetailVO> queryAllCurrOrg(BizRuleLogDetailVO bizRuleLogDetailVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<BizRuleLogDetail> bizRuleLogDetails = bizRuleLogDetailDao.queryAllCurrOrgByPage(bizRuleLogDetailVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:"+bizRuleLogDetails.size());
		List<BizRuleLogDetailVO> list = null;
		try {
			pageSet(bizRuleLogDetails, bizRuleLogDetailVo);
			list = (List<BizRuleLogDetailVO>) beansCopy(bizRuleLogDetails, BizRuleLogDetailVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<BizRuleLogDetailVO> queryAllCurrDownOrg(BizRuleLogDetailVO bizRuleLogDetailVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<BizRuleLogDetail> bizRuleLogDetails = bizRuleLogDetailDao.queryAllCurrDownOrgByPage(bizRuleLogDetailVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:"+ bizRuleLogDetails.size());
		List<BizRuleLogDetailVO> list = null;
		try {
			pageSet(bizRuleLogDetails, bizRuleLogDetailVo);
			list = (List<BizRuleLogDetailVO>) beansCopy(bizRuleLogDetails, BizRuleLogDetailVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}

	/**
	 * 启新事务，用于记录规则执行结果日志
	 * 避免正常流程异常，导致事务回滚
	 * @param ruleBean
	 * @param ruleIds
	 */
	public void newTransLogBizRuleDetailResult(RuleBean ruleBean) {

		String bizSerno = ruleBean.getBizSerno(); //业务流水号

		Map<String, Object> collResult = ruleBean.getOutput();
		// 取去执行结果
		for (Map.Entry<String, Object> entry : collResult.entrySet()) {
			String ruleCollId = entry.getKey(); //规则集id
			SRuleCollInfo collInfo = sRuleCollInfoDao.queryByRuleCollId(ruleCollId); //查询规则集信息 到这里应必须能查到规则集信息

			Object objVal = entry.getValue(); //规则集明细执行结果 map

            Map<String, Object> executMap = ruleBean.getExecu() == null ? new HashMap<>(0) : ruleBean.getExecu();
			Map<String, Object> collExecu = MapUtils.getMap(executMap, ruleCollId); // 规则集执行值
            collExecu = collExecu == null ? new HashMap<>(0) : collExecu;

			Map<String, RuleResultBean> valMap = (Map<String, RuleResultBean>) objVal;
			// 遍历规则明细结果
			for (Map.Entry<String, RuleResultBean> dtlEntry : valMap.entrySet()) {
				String ruleId = dtlEntry.getKey(); // 规则id
				RuleResultBean resultBean = dtlEntry.getValue();
				BizRuleLogDetail logDetail = new BizRuleLogDetail();
				logDetail.setBizSerno(bizSerno); // 业务流水号
				logDetail.setLogId(BizUtil.getUUID("D")); //日志明细主键
				logDetail.setRuleCollId(ruleCollId); //规则集id
                logDetail.setRuleId(ruleId); // 规则id
				// 规则执行时参数
				Map<String, Object> param = MapUtils.getMap(ruleBean.getParam(), ruleId);
				String ruleName = MapUtils.getString(param, RuleBean.RULE_NAME_KEY); //规则名称
				String ruleType = MapUtils.getString(param, RuleBean.RULE_TYPE_KEY); //规则类型
				logDetail.setRuleName(ruleName);
				// 拷贝map 去掉规则名称key
				if (param instanceof HashMap) {
					param = (Map<String, Object>) ((HashMap)param).clone();
				} else {
					param = JSON.parseObject( JSON.toJSONString(param), Map.class);
				}
				param.remove(RuleBean.RULE_NAME_KEY);
				param.remove(RuleBean.RULE_TYPE_KEY);

				logDetail.setParamVal(JSON.toJSONString(param)); // 规则执行时参数
				logDetail.setExeResult(resultBean.getExecuteReslut()); // 规则执行结果
				logDetail.setExeVal(getExeVal(collExecu, ruleId)); // 取规则执行时值
				logDetail.setRuleExeDt(resultBean.getExecDt()); // 规则执行时间

                // 回写resultBean
                resultBean.setRuleName(ruleName);
                resultBean.setRuleType(ruleType);
                resultBean.setParamVal(logDetail.getParamVal());
                resultBean.setExeVal(logDetail.getExeVal());

                if (collInfo != null) {
					resultBean.setRuleCollDesc(collInfo.getRuleCollDesc());
					resultBean.setRuleCollType(collInfo.getRuleCollType());
				}
				// 插库
				bizRuleLogDetailDao.insertBizRuleLogDetail(logDetail);
			}

		}
	} // end newTrans

	/**
	 * 返回执行时记录的值的json
	 * @param collExecu
	 * @param ruleId
	 * @return
	 */
	private String getExeVal(Map<String, Object> collExecu, String ruleId) {
		Object ruleVal = collExecu.get(ruleId);
		if (ruleVal == null) {
			return "";
		} else {
			return JSON.toJSONString(ruleVal, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty);
		}
	}
}
